
//
//  FancyTools.swift
//  Fancyswap
//
//  Created by Karim Safraoui on 2015-03-15.
//  Copyright (c) 2015 Jonathan Muschalle. All rights reserved.
//

import Foundation
import UIKit

class FancyTools{
    
    var url     : String = "http://api.fancyswap.com/rest/1.0/"
    
    
    func web_service(   completionHandler: (JSON) -> (),    type_protocol :String,
                        rest_fancy_end_point :String,       params :[String:String] ,
                        encodeJson: Bool )
    {
        var json_rep = JSON(["status":0,"message":"unkown"])
 
        if( !Authentification.getToken().isEmpty ){
            
            println("adding token \(Authentification.getToken())")
            Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders = ["Authorization":fancy_token]
        }
        
        let __encoding = encodeJson     == true     ? ParameterEncoding.JSON  : ParameterEncoding.URL
        let __method   = type_protocol  == "POST"   ? Method.POST             : Method.GET
        let __url      = self.url + rest_fancy_end_point
        
        request(    __method,               /* protocol */
                    __url,                  /* url de base + end point rest api */
                    parameters: params,     /* params */
                    encoding: __encoding    /* encoder les params en format json OU pas */
                )
                .responseJSON { (request, data, JSON_REPONSE, error) in
                    
                    if JSON_REPONSE != nil {
                        
                        completionHandler( JSON( JSON_REPONSE! ) )
                    }
                    else{
                        
                        self.alert_push("Attention", msg: "unkown bug")
                        println(error)
                        completionHandler( JSON(["status":0,"message":"unkown bug"]) )
                    }
                }
    }
    
    func alert_push(titre:String, msg: String ){
        
            let alert = UIAlertView()
            alert.title = titre
            alert.message = msg
            alert.addButtonWithTitle("Ok")
            alert.show()
    }
    
    class func authentication(sender: AnyObject) {
        
        let z = Authentification()
        
        if( z.isLoggedIn() == false ){
            
            var storyboard = UIStoryboard(name: "Authentication", bundle: nil)
            var controller = storyboard.instantiateViewControllerWithIdentifier("authentication") as UIViewController
            sender.presentViewController(controller, animated: true, completion: nil)
        }
        
    }
    
    class func isLogged() -> Bool {
        let z = Authentification()
        return z.isLoggedIn()
    }
}
